package com.feinno.module.security.web;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.feinno.framework.common.dao.support.PageInfo;
import com.feinno.framework.common.web.AbstractJQueryEntityController;
import com.feinno.framework.common.web.support.JsonListResult;
import com.feinno.framework.utils.mapper.JsonMapper;
import com.feinno.module.security.domain.Resource;
import com.feinno.module.security.domain.Role;
import com.feinno.module.security.service.ResourceService;
import com.feinno.module.security.service.RoleService;
import com.feinno.module.security.shiro.realm.ShiroDbRealm;

@Controller
@RequestMapping(value = "/manage/system/role")
public class JsonRoleController extends
		AbstractJQueryEntityController<Role, RoleService> {

	@Autowired
	@SuppressWarnings("unused")
	private RoleService roleService;
	@Autowired
	private ResourceService resourceService;
	@Autowired
	private ShiroDbRealm shiroDbRealm;

	@RequestMapping(value = { "listJson1" })
	@ResponseBody
	public String listJson1(HttpServletRequest request,
			HttpServletResponse response) {
		JsonListResult<Role> result = new JsonListResult<Role>();
		try {
			result.appendData(referenceData(request));
			PageInfo<Role> pageInfo = doList(request, response);
			result.setTotal(pageInfo.getTotalCount());
			result.setRows(pageInfo.getPageResults());
		} catch (Exception e) {
			handleException(result, "分页查询", e);
		}
		String resultBody = JsonMapper.nonDefaultMapper().toJson(result);
		return resultBody;
	}

	@Override
	protected Role onSave(HttpServletRequest request,
			HttpServletResponse response, Model model, Role entity,
			boolean isCreate) throws Exception {
		String[] resourceIds = request.getParameterValues("resourceId");
		if (resourceIds != null && resourceIds.length > 0) {
			Set<Resource> resources = new HashSet<Resource>();
			for (String resourceId : resourceIds) {
				resources.add(resourceService.get(Long.valueOf(resourceId)));
			}
			entity.setRescs(resources);
		}else{
			entity.setRescs(null);
		}
		return super.onSave(request, response, model, entity, isCreate);
	}

	@Override
	protected void referenceData(HttpServletRequest request,
			Map<String, Object> model) {

	}

}
